<?php

namespace app\api\controller;

use app\admin\model\Config;
use app\common\controller\ApiBase;
use app\Constant\ApiConstant;
use app\model\DistributionSetting;
use app\model\GoodsContentArticle;
use app\model\GoodsContentCategory;
use app\model\GoodsContentGoods;
use Exception;
use think\facade\Request;
use think\response\Json;
use Wechat\CommerceApp;

class Content extends ApiBase
{
	public function category()
	{
		$lists = GoodsContentCategory::field('id, pid, title, type')
			->where('status', 1)
			->order('sort', 'asc')
			->select()->toArray();
		//将子分类放到父级分类下children字段下面
		$categoryTree = buildCategoryTree($lists);
		return $this->callback(ApiConstant::SUCCESS, 'success', $categoryTree);
	}


	/**
	 * 列表
	 *
	 * @return Json
	 */
	public function list()
	{
		$type        = Request::get('type/d');
		$category_id = Request::get('category_id/d');
		if (empty($type) || empty($category_id)) {
			return $this->callback(ApiConstant::SUCCESS, 'success');
		}
		$page      = Request::get('page/d') ?: 1;
		$page_size = Request::get('page_size') ?: 10;
		$keyword   = Request::get('keyword');
		$user      = \app\model\User::field('id, level')->where('token', $this->token)->find();
		$level     = $user['level'] ?? 1;

		if ($type == 1) {
			$query = GoodsContentGoods::field('cg.id, cg.comment_text, cg.create_time, cg.goods_id, g.product_id, g.shop_appid, g.head_supplier_appid, g.title, g.product_promotion_link, g.sale_price, g.commission, g.subsidy_commission, g.head_imgs, g.share_text, g.image')
				->alias('cg')
				->leftJoin('goods g', 'g.id = cg.goods_id')
				->withAttr('create_time', function ($value) {
					return date('Y-m-d H:i', $value);
				})
				->where('cg.status', 1)
				->where('cg.category_id', $category_id)
				->order('cg.sort', 'asc')
				->order('cg.id', 'desc');
		} else {
			$query = GoodsContentArticle::field('id, content, images, create_time')
				->where('status', 1)
				->where('category_id', $category_id)
				->order('sort', 'asc')
				->order('id', 'desc');
		}
		if (!empty($keyword)) {
			if ($type == 1) {
				$query->where('g.title', 'like', "%{$keyword}%");
			} else {
				$query->where('content', 'like', "%{$keyword}%");
			}
		}
		$total = $query->count();
		$lists = [];
		if ($total) {
			$setting = DistributionSetting::where('uuid', 'content')->value('value');
			$name    = $avatar = '';
			if ($setting) {
				$setting = json_decode($setting, true);
				$name    = $setting['title'] ?? '';
				$avatar  = !empty($setting['image']) ? get_file_path($setting['image'], 1) : '';
			}
			if ($type == 1) {
				$lists = $query
					->withAttr('sale_price', function ($value) {
						return $value > 0 ? number_format($value / 100, 2) : "0.00";
					})
					->withAttr('head_imgs', function ($value) {
						return $value ? json_decode($value, true) : [];
					})
					->withAttr('commission', function ($value, $data) use ($level) {
						if ($value > 0) {
							//如果用户分销等级是2级，则重新计算佣金
							$setting = DistributionSetting::getLevelInfo($level, 1);
							$ratio   = $setting['ratio'] / 100;
							$price   = round($value * $ratio);
						} else {
							$price = $value;
						}
						return $price > 0 ? number_format($price / 100, 2) : "0.00";
					})
					->page($page, $page_size)
					->select();
			} else {
				$lists = $query
					->withAttr('images', function ($value) {
						$images = [];
						if ($value) {
							$arr = explode(',', $value);
							foreach ($arr as $v) {
								$images[] = get_file_path($v, 1);
							}
						}
						return $images;
					})
					->page($page, $page_size)
					->select()->toArray();
			}
			foreach ($lists as &$item) {
				$item['name']   = $name;
				$item['avatar'] = $avatar;
				unset($item['subsidy_commission']);
			}
		}
		$res = [
			'total' => $total,
			'list'  => $lists,
		];
		return $this->callback(ApiConstant::SUCCESS, 'success', $res);
	}

	public function info()
	{
		$id   = Request::get('id');
		$user = \app\model\User::field('id, level, sharer_appid')->where('token', $this->token)->find();
		if (empty($user)) {
			return $this->callback(ApiConstant::NO_LOGIN, '用户未登录');
		}
		$level = $user['level'];

		$info = \app\model\Feed::field('id, talent_appid, export_id, product_id, product_name, product_img_url, product_price, commission')
			->where('id', $id)
			->withAttr('product_price', function ($value) {
				return $value > 0 ? number_format($value / 100, 2) : "0.00";
			})
			->withAttr('commission', function ($value, $data) use ($level) {
				if ($value > 0) {
					//如果用户分销等级是2级，则重新计算佣金
					$setting = DistributionSetting::getLevelInfo($level, 1);
					$ratio   = $setting['ratio'] / 100;
					$price   = round($value * $ratio);
				} else {
					$price = $value;
				}
				return $price > 0 ? number_format($price / 100, 2) : "0.00";
			})
			->find();
		if (empty($info)) {
			return $this->callback(ApiConstant::FAILURE, '没有数据');
		}
		$feed_token = $promoter_share_link = '';
		try {
			$mini_program_appid = Config::where('name', 'wx_xcx_appid')->value('value');
			$feed_info          = CommerceApp::getInstance()->getFeedInfo($info['talent_appid'], $mini_program_appid, $info['export_id'], $user['sharer_appid']);
			if (!empty($feed_info[0])) {
				$feed_info           = $feed_info[0];
				$export_id           = $feed_info['export_id'];
				$feed_token          = $feed_info['feed_token'];
				$promoter_share_link = $feed_info['promoter_share_link'];
				$info['export_id']   = $export_id;
			}
		} catch (Exception $e) {
		}
		$info['feed_token']          = $feed_token;
		$info['promoter_share_link'] = $promoter_share_link;
		return $this->callback(ApiConstant::SUCCESS, 'success', $info);
	}

}
